package simpleftp.server;

import java.net.ServerSocket;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Simple TCP server creating threads to handle client connections
 * 
 * @author lom
 */
public class FTPServerMain {

	/**
	 * Listening port
	 */
	public static final int PORT = 7802;
	/**
	 * Maximum number of users at the same time on the server
	 */
	private static final int MAX_USERS = 50;
	/**
	 * Socket to handle connection
	 */
	private static ServerSocket socket;

	public static void main(String argv[]) throws Exception {
		// Create a pool of thread up to MAX_USERS threads
		int poolSize = MAX_USERS;
		ExecutorService executorPool = Executors.newFixedThreadPool(poolSize);
		CompletionService<Void> completionPool = new ExecutorCompletionService<Void>(executorPool);
		
		try {
			socket = new ServerSocket(PORT);
			System.out.println("Server up and running.");
			FTPServer.setDebug(true);
			while (true) {
				// Create a new thread for each accepted connection
				FTPServer server = new FTPServer(socket.accept());
				completionPool.submit(server);
			}
		} finally {
			if (socket != null) {
				socket.close();
			}
		}
	}
}
